package utils

import (
	"errors"
	"fmt"
	"net/http"

	ecode2 "server/app/ecode"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"server/pkg/ecode"
)

type resp struct {
	Code    int
	Message string
	Data    interface{}
}

func Success(c *gin.Context, data ...interface{}) {
	var d interface{}
	if len(data) > 0 {
		d = data[0]
	}
	c.JSON(http.StatusOK, resp{
		Code:    200,
		Message: "success",
		Data:    d,
	})
}

func Failed(c *gin.Context, err error) {
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = fmt.Errorf("数据异常")
	}

	code := 500
	if e, ok := err.(*ecode.Error); !ok {
		// TODO log
		err = ecode2.ErrDefault
	} else {
		code = e.Code()
	}

	c.JSON(http.StatusOK, resp{
		Code:    code,
		Message: err.Error(),
		Data:    nil,
	})
}
